<?php

namespace app\api\controller\income;


use addons\wanlshop\library\WanlPay\ProfitSharingCurl;
use addons\wanlshop\library\WanlPay\ProfitSharingSign;
use app\api\model\wanlshop\Goods;
use app\api\model\wanlshop\Shop;
use app\api\model\wanlshop\Third;
use app\common\model\User;
use think\Db;
use think\Exception;
use think\Log;

class Apply extends \app\common\controller\Api
{
    protected $noNeedRight = ['*'];
    protected $noNeedLogin = [];
    private $sign = null;
    private $curl = null;

    protected function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->sign = new ProfitSharingSign();
        $this->curl = new ProfitSharingCurl();
    }

    public function addOrder()
    {
        $user = $this->auth->id;
        $goods_id = input('goods_id');  // 商品ID
        $price = input('price');  // 投资金额

        // 商品ID
        $goods = (new Goods())->where('id',$goods_id)->find();
        if (!$goods){
            $this->error('商品不存在');
        }
        // 判断商品是否在投
        $apply = Db::name('invest_apply_for')
            ->where(['goods_id'=>$goods_id])
            ->where('status','in',['through','pending'])
            ->find();
        if (!empty($apply)){
            $this->error('商品在投中');
        }
        // 查找商品商户
        $shop = (new Shop())->where('id',$goods['shop_id'])->find();
        if (!$shop){
            $this->error('商户不存在');
        }
        // 判断商户账号
        $wechat_pay = Db::name('user_wechat_pay')->where(['user_id'=>$shop['user_id']])->find();
        if (!$wechat_pay){
            $this->error('商户未配置支付信息');
        }

        // 判断商品最低投资金额
        if ($goods['investment_cost'] <= 0){
            $this->error('商品未设置投资金额，暂不可投');
        }
        if ($goods['investment_cost'] > $price){
            $this->error('投资金额不可低于最低投资金额');
        }

        // 判断金额
        $money = User::where('id',$user)->value('money');
        if ($money < $price){
            $this->error('投资金额不足，请充值');
        }

        Db::startTrans();
        try {
            $type = $user == $shop['user_id']?'shop':'invest'; //invest=第三方投资人,shop=商户自投
            // 扣除金额
            User::money(-$price,$user,'用户投资'.$goods_id);
            // 添加分账人
            $this->addAccount($wechat_pay,$type);
            // 添加记录
            $time = time();
            $applyForData = [
                'user_id' => $user,
                'goods_id' => $goods_id,
                'shop_id' => $shop['id'],
                'shop_user_id' => $shop['user_id'],
                'is_invest' =>  $type,
                'status' => 'pending',
                'createtime' => $time,
                'updatetime' => $time,
            ];
            Db::name('invest_apply_for')->insert($applyForData);
            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
            $this->error($exception->getMessage());
        }

        $this->success('申请成功，等待审核');
    }

    /**
     * @param $wechat_pay
     * @param $type
     * @return array|false
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function addAccount($wechat_pay,$type){

        // 判断投资自投还是资方
        $receiver = [];
        if ($type == 'invest'){
            // 投资人的openid
            $third = (new Third())->where([
                'user_id'=>$this->auth->id,
            ])
                ->where('openid','<>','')
                ->find();
            if (!$third || !$third['openid']){
                \exception('投资人无可分账信息');
            }
            // 查看user_wechat_pay是否存在openid
            // 投资人
            $receiver[] = array(
                'type'=>'PERSONAL_OPENID',
                'account'=>$third['openid'],
                'name'=>'',
                'relation_type'=>'USER',
            );
        }
        // 推荐人
        $user = User::get($this->auth->id);
        if ($user['referrer']){
            // 查找推荐人的收款方式
            $third = (new Third())->where([
                'user_id'=>$user['referrer'],
            ])
                ->where('openid','<>','')
                ->find();
            if (!$third || !$third['openid']){
                \exception('投资人无可分账信息');
            }
            // 推荐人
            $receiver[] = array(
                'type'=>'PERSONAL_OPENID',
                'account'=>$third['openid'],
                'name'=>'',
                'relation_type'=>'USER',
            );
        }
        // 平台
        $receiver[] = array(
            'type'=>'PERSONAL_OPENID',
            'account'=>'ozawL5Ie8JivCe6XhBdw1nIWpX7E',
            'amount'=>2,
            'description'=>"商品平台分成",
        );

        foreach ($receiver as $item){
            $this->sendAdd($item);
        }
        return true;
    }

    private function sendAdd($receiver){
        $receiver = json_encode($receiver,JSON_UNESCAPED_UNICODE);
        $postArr = array(
            'appid'=>'wx0b5509f48f674fc5',
            'mch_id'=>'1639993260',
            'nonce_str'=>md5(time() . rand(1000, 9999)),
            'receiver'=>$receiver
        );

        $sign = $this->sign->getSign($postArr, 'HMAC-SHA256','Sdchungunke1593deikldxldokdesmgd');
        $postArr['sign'] = $sign;
        //3.发送请求
        $url = 'https://api.mch.weixin.qq.com/pay/profitsharingaddreceiver';
        $postXML = $this->toXml($postArr);
        $curl_res = $this->curl->post($url,$postXML);
        $ret = $this->toArray($curl_res);
        Log::error($ret);
        return $ret;
    }

    /**
     * @function 将array转为xml
     * @param array $values
     * @return string|bool
     * @author xiewg
     **/
    public function toXml($values)
    {
        if (!is_array($values) || count($values) <= 0) {
            return false;
        }

        $xml = "<xml>";
        foreach ($values as $key => $val) {
            if (is_numeric($val)) {
                $xml.="<".$key.">".$val."</".$key.">";
            } else {
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }

    /**
     * @function 将xml转为array
     * @param string $xml
     * @return array|false
     * @author xiewg
     */
    public function toArray($xml)
    {
        if (!$xml) {
            return false;
        }

        // 检查xml是否合法
        $xml_parser = xml_parser_create();
        if (!xml_parse($xml_parser, $xml, true)) {
            xml_parser_free($xml_parser);
            return false;
        }

        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);

        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        return $data;
    }
}